package com.yanlin;

import java.io.IOException;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class GuiceClassLoader extends URLClassLoader {

    /**
     * jar的文件后缀
     */
    private static final String jar_suffix = ".jar";


    /**
     * jar的URI后缀
     */
    private static final String jar_uri_suffix = "!/";

    /**
     * jar的URI文件协议
     */
    private static final String jar_protocol = "jar:file:";

    private static final String base_prefix = "guicestudy";

    private static final String dependency = "dependency";

    private static final String dependency_lib = "lib";

    private static final String getJar_suffix = "yanlin";

    private static Set<String> system_packages_prefix_list = new HashSet<>();

    static {
        system_packages_prefix_list.add("java.");
        system_packages_prefix_list.add("javax.");
    }


    private Path tempUnpackDirectory;

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {

        System.out.println("findClass:" + name);
        for (String s : system_packages_prefix_list) {
            if (name.startsWith(s)) {
                return GuiceClassLoader.class.getClassLoader().loadClass(name);
            }
        }
        return super.findClass(name);
    }

    public GuiceClassLoader() throws IOException {
       this(null);
    }

    public GuiceClassLoader(Path tempUnpackDirectory) throws IOException {
        super(new URL[]{}, null);
        this.tempUnpackDirectory = tempUnpackDirectory;
        String resourcePath = GuiceClassLoader.class.getResource("").toString();

        int index = resourcePath.indexOf(jar_uri_suffix);

        String baseJarUrl = resourcePath.substring(0, index + jar_uri_suffix.length());

        String filePath = resourcePath.substring(index + jar_uri_suffix.length());

        index = filePath.indexOf(jar_uri_suffix);

        if (index == -1) {
            addbaseJar(baseJarUrl);
        }

    }

    private void addbaseJar(String baseJarUrl) throws IOException {
        URL url = new URL(baseJarUrl);
        super.addURL(url);

        JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();

        try (JarFile jarFile = jarURLConnection.getJarFile()){
            Enumeration<JarEntry> entries = jarFile.entries();
            Path filePath = null;

        }

    }


}
